<?php

App::uses('AppModel', 'Model');
App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationAccount Model
 *
 * @property Organisation $Organisation
 */
class OrganisationAccount extends CompositeKeyModel {

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'MemberAccount' => array(
            'className' => 'MemberAccount',
            'foreignKey' => 'member_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
    );

    public function attempt_login($username, $password) {
        $accounts = $this->find('all', array(
            'contain' => array(
                'Organisation' => array(
                    'OrganisationSubscription' => array(
                        'limit' => 1,
                        'order' => array('subscription_start_dt' => 'desc')
                    )
                )
            ),
            'conditions' => array(
                'OrganisationAccount.username' => $username,
                'OrganisationAccount.active' => 1
            )
        ));

        foreach ($accounts as $account) {
            if ($account['OrganisationAccount']['password'] == md5($password . $account['OrganisationAccount']['pass_salt'])) {
                // todo other things
                return $account;
            }
        }

        return false;
    }

    public function getOrganisationAcounts($organisation_id) {
        return $this->find('all', array(
            'fields' => array('type', 'first_name', 'last_name', 'username'),
            'conditions' => array(
                'OrganisationAccount.organisation_id' => $organisation_id,
                'OrganisationAccount.active' => 1
            ),
            'recursive' => -1
        ));
    }

}
